﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CS2102_Music.Logic
{
    public partial class Logic
    {
        private DbConnector databaseConnector;
        private static Logic Instance = null;
        public static Logic GetInstance(DbConnector database)
        {
            if (Instance == null)
                Instance = new Logic(database);
            return Instance;
        }

        protected Logic(DbConnector database)
        {
            databaseConnector = database;
        }
        public bool AuthenticateAdmin(int userID, string password)
        {
            String query = "SELECT admins.password FROM admins WHERE employee.ID = " + userID;
            //MySqlDataReader result = databaseConnector.ExecuteReaderQuery(query);
            QueryResult result = databaseConnector.ExecuteQuery(query);

            if (result.RowCount == 0)
                return false;
            else
            {
                String resultPassword = result.At(0, 0);
                if (MatchHash(resultPassword, password))
                    return true;
                else
                    return false;
            }
        }
        public bool AuthenticateCustomer(int userID, string password)
        {
            String query = "SELECT users.password FROM users WHERE users.email = " + userID;
            //MySqlDataReader result = databaseConnector.ExecuteReaderQuery(query);
            QueryResult result = databaseConnector.ExecuteQuery(query);

            if (result.RowCount == 0)
                return false;
            else
            {
                String resultPassword = result.At(0, 0);
                if (MatchHash(resultPassword, password))
                    return true;
                else
                    return false;
            }
        }

        public static string CreateHash(string unHashed)
        {
            // create encrypt service provider
            //System.Security.Cryptography.sh
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            // Convert string to byte array
            byte[] data = System.Text.Encoding.ASCII.GetBytes(unHashed);
            // get encrypted byte array
            data = x.ComputeHash(data);
            return System.Text.Encoding.ASCII.GetString(data);
        }

        public static bool MatchHash(string hashData, string unhashedData)
        {
            // Hash the unhashed data
            unhashedData = CreateHash(unhashedData);
            if (unhashedData == hashData)
                return true;
            else
                return false;
        }

    }
}